package com.cskaoyan.mall.dao.implement;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.mall.model.bo.AdminAddBO;
import com.cskaoyan.mall.model.bo.AdminChangePwdBO;
import com.cskaoyan.mall.dao.AdminDao;
import com.cskaoyan.mall.model.sql.Admin;
import com.cskaoyan.mall.model.sql.Result;
import com.cskaoyan.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminDaoImpl implements AdminDao {
    private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
    /**
     * login 是登录功能：利用QueryRunner.query 查询并返回有无此admin
     * @param admin 管理员对象，有[id,email,nickname,pwd]
     * @return 200->成功  500->失败
     */
    @Override
    public Admin login(Admin admin) {
            //query 中 BeanHandler 利用admin.get***  参数 和 Admin.class 封装一个新的对象并与sql语句结果比较，有则返回此对象，无则返回null
        Admin query = null;
        try {
            query = queryRunner.query("select * from admin where email = ? and pwd = ?",
                    new BeanHandler<>(Admin.class),
                    admin.getEmail(),
                    admin.getPwd());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * allAdmins 表示获取所有的admin信息
     * @return  返回参数是List<Admin>
     */
    @Override
    public List<Admin> allAdmins(){
        List<Admin> admins = null;
        try {
            admins = queryRunner.query("select * from admin", new BeanListHandler<Admin>(Admin.class));
        }catch (SQLException e){
            e.printStackTrace();
        }
        return admins;
    }

    @Override
    public void addAdminss(AdminAddBO addBO) {
        try {
            queryRunner.update("insert into admin(email,pwd,nickname) value(?,?,?)",
                    addBO.getEmail(),
                    addBO.getPwd(),
                    addBO.getNickname()
                    );
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteAdmins(String id) {
        try {
            queryRunner.update("delete from admin where id = ?",
                    id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Admin getAdminsInfo(String id) {
        Admin ad = null;
        try {
            ad = queryRunner.query("select * from admin where id = ?",
                    new BeanHandler<Admin>(Admin.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ad;
    }

    @Override
    public void updateAdminss(Admin admin) {
        try {
            queryRunner.update("update admin set email = ?, pwd = ? , nickname = ? where id = ? ",
                    admin.getEmail(),admin.getPwd(),admin.getNickname()
                    ,admin.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public Result changePwd(AdminChangePwdBO changePwdBO) {
        Result result = new Result();
        //先查询旧密码对不对
        Admin queryAdmin = new Admin();
        try {
             queryAdmin = queryRunner.query("select pwd from admin where nickname = ?",
                    new BeanHandler<>(Admin.class),
                    changePwdBO.getAdminToken());
            if(queryAdmin==null){
                result.setMessage("你的代码有问题");
                return result;
            } else{
            if(!queryAdmin.getPwd().equals(changePwdBO.getOldPwd())){
                 result.setCode(10000);
                 result.setMessage("旧密码不正确！");
                 return result;
             }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //再修改新密码
        if(!changePwdBO.getNewPwd().equals(changePwdBO.getConfirmPwd())){
            result.setCode(10000);
            result.setMessage("两次新密码输入不一致！");
            return result;
        }
        try {
            queryRunner.update("update admin set pwd = ? where nickname = ?",changePwdBO.getNewPwd(),
                    changePwdBO.getAdminToken());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        result.setCode(200);
        result.setMessage("密码修改成功！");
        return result;
    }

    /** 区别于上面，如何优化
     * 1.当账号搜索栏有数据： select * from admin where email like ?
     * 2.当昵称搜索栏有数据: select * from admin where nickname like ?
     * 3.当账户、昵称都有数据： select * from admin where email like ? and nickname like ?
     *      动态sql的思想
     * @param admin
     * @return
     */
    @Override
    public List<Admin> getSearchAdmins(Admin admin) {
        Map<String,Object> result = getDynamicSql(admin);
        String sql = (String) result.get("sql");
        List<String> params = (List<String>) result.get("params");
        List<Admin> admins = null;
        try {
            admins = queryRunner.query(sql, new BeanListHandler<Admin>(Admin.class), params.toArray());// params是一个List 得转成数组
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return admins;
    }

    private Map<String, Object> getDynamicSql(Admin admin) {
        String base = "select * from admin where 1 = 1";
        //解决参数问题
        List<String> params = new ArrayList<>();
        //解决语句问题
        if(!StringUtils.isEmpty(admin.getEmail())){ //StringUtils工具类复习
            base = base + " and email like ?";
            params.add("%"+admin.getEmail()+"%");//模糊查询参数
        }
        if(!StringUtils.isEmpty(admin.getNickname())){ //StringUtils工具类复习
            base = base + " and nickname like ?";
            params.add("%"+admin.getNickname()+"%");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("sql",base);
        map.put("params",params);
        return map;
    }
}
